package com.dragon.english_practice_back.service.impl;


import com.dragon.english_practice_back.entity.TableColumnInfo;
import com.dragon.english_practice_back.mapper.TableColumnMapper;
import com.dragon.english_practice_back.service.TableAndColumnNameVerifyService;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@AllArgsConstructor
public class TableAndColumnNameVerifyServiceImpl implements TableAndColumnNameVerifyService {

    private static Map<String, List<String>> tableColumnNameMap;
    private static boolean usable = false;
    TableColumnMapper tableColumnMapper;


    @Override
    public boolean verifyTableName(String tableName) {
        if (!usable) {
            return true;
        }
        return tableColumnNameMap.containsKey(tableName);
    }

    @Override
    public boolean verifyColumnName(String tableName, String columnName) {
        if (!usable) {
            return true;
        }
        if (tableColumnNameMap.containsKey(tableName)) {
            return tableColumnNameMap.get(tableName).contains(columnName);
        }
        return false;
    }

    @Override
    public List<String> getAllColumnNames(String tableName) {
        if (!usable) {
            return null;
        }
        if (tableColumnNameMap.containsKey(tableName)) {
            return tableColumnNameMap.get(tableName);
        }
        return null;
    }


    @PostConstruct
    public void getTableColumn() {
        try {
            List<TableColumnInfo> tableColumnInfoList = tableColumnMapper.getColumnName();

            tableColumnNameMap = new HashMap<>();

            tableColumnInfoList.forEach(tableColumnInfo -> {
                if (tableColumnNameMap.containsKey(tableColumnInfo.getTableName())) {
                    tableColumnNameMap.get(tableColumnInfo.getTableName()).add(tableColumnInfo.getColumnName());
                }
                else {
                    List<String> columnNameList = new ArrayList<>();
                    columnNameList.add(tableColumnInfo.getColumnName());
                    tableColumnNameMap.put(tableColumnInfo.getTableName(), columnNameList);
                }
            });

            log.info("tables and columns load success");

            usable = true;
        }
        catch (Exception e) {
            log.error("getTableColumn error:", e);
        }

    }
}
